package com.zjsd.mobile.controller;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.mapper.SysOperLogMapper;
import com.zjsd.sqeybusiness.dto.WechatDTO;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/wechat")
public class WeChatController {

    @Autowired
    private SysOperLogMapper sysOperLogMapper;
    // 这里的token需要与微信公众号后台配置的Token一致
    private static final String TOKEN = "sqeybusiness";
    //private static final String APP_ID = "wx4cb99b1bdc687e06"; // 测试
    private static final String APP_ID = "wxd81a6bd295facda3"; // 正式
    //private static final String APP_SECRET = "390f677950880eb8c15be7e6c5d05e61"; // 测试
    private static final String APP_SECRET = "97bceab2781722d49b12406bdb24ffd2"; // 测试
    @GetMapping
    public String wechatVerify(@RequestParam String signature,
                               @RequestParam String timestamp,
                               @RequestParam String nonce,
                               @RequestParam String echostr) {
        List<String> params = Arrays.asList(TOKEN, timestamp, nonce);
        Collections.sort(params);
        String joined = params.stream().collect(Collectors.joining());
        String sha1 = getSha1(joined);
        System.out.println("sha1:" + sha1);
        if (signature.equals(sha1)) {
            System.out.println("验证成功:" + echostr);
            return echostr;
        }
        return "";
    }

    private String getSha1(String str) {
        try {
            java.security.MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
            digest.update(str.getBytes());
            byte messageDigest[] = digest.digest();
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String h = Integer.toHexString(0xFF & b);
                while (h.length() < 2) h = "0" + h;
                hexString.append(h);
            }
            return hexString.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @GetMapping("/getAccessToken")
    public AjaxResult getAccessToken(WechatDTO wchatDTO1) {
        WechatDTO wechatDTO = new WechatDTO();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID +
                "&secret=" + APP_SECRET +
                "&code=" + wchatDTO1.getCode() +
                "&grant_type=authorization_code";
        System.out.println("tokenUrl:" + url);
        SysOperLog sysOperLog = new SysOperLog();
        sysOperLog.setTitle("获取微信token");
        sysOperLog.setOperName("获取微信token");
        sysOperLog.setOperParam("code:" + wchatDTO1.getCode());
        sysOperLog.setBusinessType(1);
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            // 发送请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                    sysOperLog.setJsonResult(result);
                    sysOperLogMapper.insertOperlog(sysOperLog);
                    JsonObject jsonObject = JsonParser.parseString(result).getAsJsonObject();
                    if(jsonObject != null && jsonObject.has("access_token") && jsonObject.has("openid")){
                        String accessToken = jsonObject.get("access_token").getAsString();
                        String openid = jsonObject.get("openid").getAsString();
                        String refreshToken = jsonObject.get("refresh_token").getAsString();
                        wechatDTO.setRefresh_token(refreshToken);
                        System.out.println("Access Token: " + accessToken);
                        System.out.println("OpenID: " + openid);
                        wechatDTO.setAccess_token(accessToken);
                        wechatDTO.setOpenid(openid);
                    }
                    return AjaxResult.success(wechatDTO);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(wechatDTO);
    }

    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo(WechatDTO wechatDTO1) throws IOException {
        WechatDTO wechatDTO = new WechatDTO();
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + wechatDTO1.getAccess_token() +
                "&openid=" + wechatDTO1.getOpenid() +
                "&lang=zh_CN";
        System.out.println("userUrl:" + url);
        SysOperLog sysOperLog = new SysOperLog();
        sysOperLog.setTitle("获取用户信息");
        sysOperLog.setOperName("获取用户信息");
        sysOperLog.setOperParam("{ access_token:" + wechatDTO1.getAccess_token() + " , " + "openid:" + wechatDTO1.getOpenid() + "}");
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Content-Type", "application/json");

            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                    System.out.println("获取用户信息结果：" + result);
                    sysOperLog.setJsonResult(result);
                    sysOperLogMapper.insertOperlog(sysOperLog);
                    System.out.println("用户返回结果：:" + result);
                    if(StringUtils.isNotBlank(result)){
                        JsonObject jsonObject = JsonParser.parseString(result).getAsJsonObject();
                        if(jsonObject != null && jsonObject.has("nickname") && jsonObject.has("headimgurl")){
                            String nickname = jsonObject.get("nickname").getAsString();
                            String headerUrl = jsonObject.get("headimgurl").getAsString();
                            wechatDTO.setNickname(nickname);
                            wechatDTO.setHeadimgurl(headerUrl);
                            wechatDTO.setOpenid(wechatDTO1.getOpenid());
                            wechatDTO.setAccess_token(wechatDTO1.getAccess_token());
                            System.out.println("Header URL: " + headerUrl);
                            System.out.println("Nickname: " + nickname);
                        }
                    }
                    return AjaxResult.success(wechatDTO);
                }
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
        return AjaxResult.success(wechatDTO);
    }

    @GetMapping("/refreshAccessToken")
    public AjaxResult refreshAccessToken(@RequestParam String refresh_token) {
        WechatDTO wechatDTO = new WechatDTO();
        String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + APP_ID +
                "&grant_type=refresh_token" +
                "&refresh_token=" + refresh_token;
        System.out.println("refreshTokenUrl:" + url);
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            // 发送请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                    JsonObject jsonObject = JsonParser.parseString(result).getAsJsonObject();
                    if(jsonObject != null && jsonObject.has("access_token") && jsonObject.has("openid")){
                        String accessToken = jsonObject.get("access_token").getAsString();
                        String openid = jsonObject.get("openid").getAsString();
                        String newRefreshToken = jsonObject.get("refresh_token").getAsString();
                        String expiresIn = jsonObject.get("expires_in").getAsString();
                        System.out.println("New Access Token: " + accessToken);
                        System.out.println("OpenID: " + openid);
                        System.out.println("New Refresh Token: " + newRefreshToken);
                        System.out.println("Expires In: " + expiresIn);
                        wechatDTO.setAccess_token(accessToken);
                        wechatDTO.setOpenid(openid);
                        wechatDTO.setRefresh_token(newRefreshToken);
                        wechatDTO.setExpires_in(expiresIn);
                    }
                    return AjaxResult.success(wechatDTO);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(wechatDTO);
    }

    @GetMapping("/validateAccessToken")
    public AjaxResult validateAccessToken(WechatDTO wechatDTO) {
        String url = "https://api.weixin.qq.com/sns/auth?access_token=" + wechatDTO.getAccess_token() +
                "&openid=" + wechatDTO.getOpenid();
        System.out.println("validateTokenUrl:" + url);
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            // 发送请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                    JsonObject jsonObject = JsonParser.parseString(result).getAsJsonObject();
                    if(jsonObject != null && jsonObject.has("errcode")){
                        int errcode = jsonObject.get("errcode").getAsInt();
                        if (errcode == 0) {
                            wechatDTO.setErrcode("0");
                            return AjaxResult.success(wechatDTO) ;
                        } else {
                            wechatDTO.setErrcode("40003");
                            return AjaxResult.success(wechatDTO);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(wechatDTO) ;
    }
}